<template>
  <div class="custom-analysis-container">
    <el-page-header content="自定义分析配置" style="margin-bottom: 20px;"></el-page-header>

    <!-- 筛选器配置 -->
    <el-card shadow="hover" class="stat-card">
      <div slot="header">
        <span>分析条件配置</span>
      </div>
      <el-form :model="filterForm" label-width="120px" style="margin-top: 10px;">
        <el-form-item label="设备类型">
          <el-checkbox-group v-model="filterForm.deviceTypes">
            <el-checkbox label="transformer">变压器</el-checkbox>
            <el-checkbox label="switchgear">开关柜</el-checkbox>
            <el-checkbox label="cable">电缆</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
              v-model="filterForm.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="区域筛选">
          <el-select
              v-model="filterForm.region"
              multiple
              placeholder="请选择区域"
          >
            <el-option label="华东" value="east"></el-option>
            <el-option label="华北" value="north"></el-option>
            <el-option label="华南" value="south"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态标签">
          <el-select
              v-model="filterForm.status"
              multiple
              placeholder="请选择状态"
          >
            <el-option label="健康" value="health"></el-option>
            <el-option label="预警" value="warning"></el-option>
            <el-option label="异常" value="abnormal"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="generateAnalysis">生成分析</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 指标配置 -->
    <el-card shadow="hover" class="stat-card" style="margin-top: 20px;">
      <div slot="header">
        <span>指标配置</span>
      </div>
      <el-form :model="indicatorForm" label-width="120px" style="margin-top: 10px;">
        <el-form-item label="显示指标">
          <el-checkbox-group v-model="indicatorForm.selectedIndicators">
            <el-checkbox label="deviceCount">设备数量</el-checkbox>
            <el-checkbox label="faultRate">故障率</el-checkbox>
            <el-checkbox label="maintainCost">维护成本</el-checkbox>
            <el-checkbox label="energyConsumption">能耗</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="图表类型">
          <el-radio-group v-model="indicatorForm.chartType">
            <el-radio label="bar">柱状图</el-radio>
            <el-radio label="line">折线图</el-radio>
            <el-radio label="pie">饼图</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="对比维度">
          <el-select v-model="indicatorForm.compareDimension" placeholder="请选择">
            <el-option label="设备类型" value="deviceType"></el-option>
            <el-option label="区域" value="region"></el-option>
            <el-option label="时间" value="time"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 分析结果 -->
    <el-card shadow="hover" class="stat-card" style="margin-top: 20px;">
      <div slot="header">
        <span>分析结果</span>
        <el-button type="primary" size="mini" @click="saveAnalysis">保存分析</el-button>
        <el-button type="text" size="mini" @click="exportExcel">导出Excel</el-button>
      </div>
      <div v-if="!analysisResult" class="empty-result">
        <el-empty description="请点击'生成分析'按钮获取结果"></el-empty>
      </div>
      <div v-else>
        <div id="customChart" style="width: 100%; height: 400px;"></div>
        <el-table
            :data="analysisTableData"
            border
            style="width: 100%; margin-top: 20px;"
        >
          <el-table-column prop="dimension" label="维度"></el-table-column>
          <el-table-column prop="deviceCount" label="设备数量"></el-table-column>
          <el-table-column prop="faultRate" label="故障率(%)"></el-table-column>
          <el-table-column prop="maintainCost" label="维护成本(万元)"></el-table-column>
          <el-table-column prop="energyConsumption" label="能耗(kWh)"></el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { Message } from 'element-ui'

export default {
  name: 'CustomAnalysis',
  data() {
    return {
      filterForm: {
        deviceTypes: ['transformer', 'switchgear'],
        timeRange: ['2024-01-01', '2024-06-30'],
        region: ['east', 'north'],
        status: ['health', 'warning']
      },
      indicatorForm: {
        selectedIndicators: ['deviceCount', 'faultRate', 'maintainCost'],
        chartType: 'bar',
        compareDimension: 'deviceType'
      },
      analysisResult: false,
      analysisTableData: [],
      customChart: null
    }
  },
  methods: {
    generateAnalysis() {
      // TODO: 对接后端自定义分析接口
      // 示例接口：/api/statAnalysis/custom?params=...

      // 模拟返回数据
      this.analysisTableData = [
        {
          dimension: '变压器',
          deviceCount: 120,
          faultRate: 2.3,
          maintainCost: 180,
          energyConsumption: 1250000
        },
        {
          dimension: '开关柜',
          deviceCount: 230,
          faultRate: 1.8,
          maintainCost: 210,
          energyConsumption: 850000
        }
      ]

      this.renderCustomChart()
      this.analysisResult = true
    },
    renderCustomChart() {
      if (!this.customChart) {
        this.customChart = echarts.init(document.getElementById('customChart'))
      }

      const xData = this.analysisTableData.map(item => item.dimension)
      const series = []

      this.indicatorForm.selectedIndicators.forEach(indicator => {
        let name = ''
        let yAxisIndex = 0

        if (indicator === 'deviceCount') {
          name = '设备数量'
        } else if (indicator === 'faultRate') {
          name = '故障率(%)'
          yAxisIndex = 1
        } else if (indicator === 'maintainCost') {
          name = '维护成本(万元)'
        } else if (indicator === 'energyConsumption') {
          name = '能耗(kWh)'
        }

        series.push({
          name: name,
          type: this.indicatorForm.chartType,
          data: this.analysisTableData.map(item => item[indicator]),
          yAxisIndex: yAxisIndex
        })
      })

      this.customChart.setOption({
        title: { text: '', left: 'center' },
        tooltip: { trigger: 'axis' },
        legend: {
          data: series.map(item => item.name)
        },
        xAxis: {
          type: 'category',
          data: xData
        },
        yAxis: [
          { type: 'value', name: '数量/成本/能耗' },
          { type: 'value', name: '故障率(%)' }
        ],
        series: series
      })
    },
    resetFilter() {
      this.filterForm = {
        deviceTypes: [],
        timeRange: null,
        region: [],
        status: []
      }
    },
    saveAnalysis() {
      // TODO: 保存分析配置接口
      Message.success('分析配置已保存')
    },
    exportExcel() {
      // TODO: 导出Excel接口
      Message.success('Excel导出中...')
    }
  },
  beforeDestroy() {
    if (this.customChart) this.customChart.dispose()
  }
}
</script>

<style scoped>
.custom-analysis-container {
  padding: 20px;
}
.stat-card {
  height: 100%;
}
.empty-result {
  padding: 50px 0;
}
</style>